﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LGE;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace UpUp
{
    class MarketScreen : GameScreen
    {
        Character c;
        Texture2D bg;
        Button exit;
        Button play;

        // colors
        Color fontColorDescr = new Color(191, 139, 86);
        Color fontColorStat = new Color(16, 8, 101);
        Color fontColorCrystals = new Color(255, 219, 49);
        Color fontColorPrices = new Color(255, 150, 0);

        // positions
        // 0 = visor | 1 = coat | 2 = boot | 3 = spike
        Vector2 itensPos = new Vector2(204, 261);
        Vector2[] upgradeButtonPos = new Vector2[4] { new Vector2(483, 283), new Vector2(951, 283), new Vector2(483, 384), new Vector2(951, 384) };
        Vector2 backPos = new Vector2(758, 618);
        Vector2 menuPos = new Vector2(998, 618);
        Vector2[] selectedItemPos = new Vector2[4] { new Vector2(167, 255), new Vector2(645, 255), new Vector2(167, 358), new Vector2(645, 358) };
        Vector2[] barLevelPos = new Vector2[4] { new Vector2(315, 284), new Vector2(793, 284), new Vector2(315, 387), new Vector2(793, 387) };
        Vector2[] pricePos = new Vector2[4] { new Vector2(593, 292), new Vector2(1051, 292), new Vector2(593, 389), new Vector2(1051, 389) };
        Vector2 goldPos = new Vector2(343, 163);
        Vector2 maxAltitudePos = new Vector2(697, 145);
        Vector2 nTriesPos = new Vector2(916, 145);
        Vector2 itemDescrPos = new Vector2(181, 487);
        Vector2 crystalsPos = new Vector2(607, 293);

        // sprites
        Button[] upgradeButtons;
        Texture2D spriteUpgradeOff;
        Texture2D spriteItens;
        Texture2D spriteUpgradeLevel;
        Texture2D spriteSelectedUpgrade;
        Texture2D spriteCrystals;

        PlayScreen ps;

        //aux
        int mouseOnItem = -1;
        String[,] frases = new String[4, 4];

        bool showHotkeys = false;

        public MarketScreen(PlayScreen ps, Character c) : base()
        {
            this.ps = ps;
            this.c = c;
        }

        public override void LoadContent()
        {
            LoadFrases();
            bg = Engine.Load<Texture2D>("Images\\MarketScreen\\market_background");
            exit = new Button(Engine.Load<Texture2D>("Images\\MarketScreen\\menu_principal"), menuPos);
            play = new Button(Engine.Load<Texture2D>("Images\\MarketScreen\\voltar_ao_jogo"), backPos);

            upgradeButtons = new Button[4];
            Texture2D upgradeButtonSprite = Engine.Load<Texture2D>("Images\\MarketScreen\\botao_upgrade");
            for (int i = 0; i < 4; ++i) upgradeButtons[i] = new Button(upgradeButtonSprite, upgradeButtonPos[i]);

            spriteUpgradeOff = Engine.Load<Texture2D>("Images\\MarketScreen\\botao_upgrade_desabilitado");
            spriteItens = Engine.Load<Texture2D>("Images\\MarketScreen\\itens");
            spriteUpgradeLevel = Engine.Load<Texture2D>("Images\\MarketScreen\\nivel_upgrade");
            spriteSelectedUpgrade = Engine.Load<Texture2D>("Images\\MarketScreen\\mouse_over");
            spriteCrystals = Engine.Load<Texture2D>("Images\\MarketScreen\\cristais");
        }

        public override void Update(GameTime gameTime)
        {
            if (Input.KeyPressed(Keys.M)) Audio.ToggleMute();
            if (play.Clicked || Input.KeyPressed(Keys.Enter) || Input.KeyPressed(Keys.Space) || Input.ButtonPressed(Buttons.Start))
            {
                c.nSessions++;
                UpUp.isMouseVisible = false;
                ps.isMarket = false;
                ps.isLive = true;
                Audio.PlaySong("Audio\\BGM\\Play");
                return;
            }

            else if (exit.Clicked || Input.KeyPressed(Keys.Back))
                GameScreenManager.ChangeScreen(new StartScreen());

            for (int i = 0; i < 4; ++i)
                if (upgradeButtons[i].Clicked) { c.AddAtt(i); break; }

            if (UpUp.isDebug)
            {
                if (Input.KeyPressed(Keys.F2)) showHotkeys = !showHotkeys;
                else if (Input.KeyPressed(Keys.C)) c.crystals++;
                else if (Input.KeyPressed(Keys.Q)) c.attLevel[Att.Visor]++;
                else if (Input.KeyPressed(Keys.A)) c.attLevel[Att.Visor]--;
                else if (Input.KeyPressed(Keys.W)) c.attLevel[Att.Coat]++;
                else if (Input.KeyPressed(Keys.S)) c.attLevel[Att.Coat]--;
                else if (Input.KeyPressed(Keys.E)) c.attLevel[Att.Boot]++;
                else if (Input.KeyPressed(Keys.D)) c.attLevel[Att.Boot]--;
                else if (Input.KeyPressed(Keys.R)) c.attLevel[Att.Spike]++;
                else if (Input.KeyPressed(Keys.F)) c.attLevel[Att.Spike]--;
                //else if (Input.KeyPressed(Keys.O)) ps.levelHeight++;
                //else if (Input.KeyPressed(Keys.L)) ps.levelHeight--;
                //ps.levelHeight = (int)MathHelper.Clamp(ps.levelHeight, 10, 1000);
            }
        }

        /*public void ConfirmSelection()
        {
            c.nSessions++;
            ps.isMarket = false;
        }*/

        public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            // background
            spriteBatch.Draw(bg, Vector2.Zero, Color.White);

            // botões de sair e voltar pro jogo
            exit.Draw(spriteBatch);
            play.Draw(spriteBatch);

            // Item selecionado
            mouseOnItem = -1;
            for (int i = 0; i < 4; ++i)
            {
                Vector2 t = Input.MousePos - selectedItemPos[i];//new Vector2(83, 274 + i * 78);
                if (spriteSelectedUpgrade.Bounds.Contains((int)t.X, (int)t.Y))
                {
                    spriteBatch.Draw(spriteSelectedUpgrade, Input.MousePos - t, Color.White);
                    mouseOnItem = i;
                    break;
                }
            }

            // desenha os cristais dos preços
            spriteBatch.Draw(spriteCrystals, crystalsPos, Color.White);

            // desenha a imagem dos itens
            spriteBatch.Draw(spriteItens, itensPos, Color.White);

            // Barrinha laranja do nível dos upgrades
            for (int j = 0; j < 4; ++j)
                for (int i = 0; i < c.attLevel[j] && i < 3; ++i) DrawUpgradeLevel(spriteBatch, barLevelPos[j] + new Vector2(50*i, 0));

            // botões de upgrade
            for (int i = 0; i < 4; ++i)
                if (c.attLevel[i] < 0 || c.attLevel[i] > 2 || c.crystals < c.attCosts[c.attLevel[i]]) 
                    spriteBatch.Draw(spriteUpgradeOff, upgradeButtons[i].position, Color.White); 
                else 
                    upgradeButtons[i].Draw(spriteBatch);

            // stats
            spriteBatch.DrawString(UpUp.Font, c.crystals.ToString(), goldPos, fontColorCrystals);
            spriteBatch.DrawString(UpUp.Font, c.maxH.ToString() + "m", maxAltitudePos, fontColorStat);
            spriteBatch.DrawString(UpUp.Font, c.nSessions.ToString(), nTriesPos, fontColorStat);

            // prices
            for (int i = 0; i < 4; ++i)
            {
                if (c.attLevel[i] < 0 || c.attLevel[i] > 2) continue;
                int cost = c.attCosts[c.attLevel[i]];

                String text = cost.ToString();
                spriteBatch.DrawString(UpUp.Font, text, pricePos[i], fontColorPrices, 0, new Vector2(UpUp.Font.MeasureString(text).X, 0), 1, SpriteEffects.None, 0);
            }

            // frase do item 
            try { spriteBatch.DrawString(UpUp.FontDescr, Wrap(frases[mouseOnItem, (mouseOnItem > 3 ? 0 : c.attLevel[mouseOnItem])], 90), itemDescrPos, fontColorDescr); }
            catch (Exception e) { }

            // debug
            //spriteBatch.DrawString(UpUp.Font, "LevelHeight: " + ps.levelHeight, new Vector2(150, 650), Color.White);
            if (showHotkeys)
            {
                spriteBatch.Draw(GameScreenManager.blackScreen, Vector2.Zero, new Color(0f, 0f, 0f, .85f));
                spriteBatch.DrawString(UpUp.Font, "C: add crystal (for test)\n" +
                                                  "Enter: play\n" +
                                                  "Backspace: quit to StartScreen\n" +
                                                  "O/L: add or subtract LevelHeight (for test)\n" +
                                                  "Q/A: add or subtract VisorLevel (unlimited, no cost, for test)\n" +
                                                  "W/S: add or subtract CoatLevel (unlimited, no cost, for test\n" +
                                                  "E/D: add or subtract BootLevel (unlimited, no cost, for test)\n" +
                                                  "R/F: add or subtract SpikeLevel (unlimited, no cost, for test)\n" +
                                                  "Left click on (+) buttons: add upgrade level limited to 3 (costs: 1, 2, 3)\n" +
                                                  "M: toggle audio (for test)\n" +
                                                  "F2: toggle help\n" +
                                                  "F1: restart game\n" +
                                                  "Esc: exit game"
                    , new Vector2(100, 150), Color.White);
            }
        }

        public void DrawUpgradeLevel(SpriteBatch spriteBatch, Vector2 pos)
        {
            spriteBatch.Draw(spriteUpgradeLevel, pos, Color.White);
        }

        public String Wrap(String s, int limit)
        {
            String r = "";
            String line = "";
            String[] words = s.Split(' ');
            foreach (String word in words)
            {
                if ((line + word).Length > limit)
                {
                    r += line + "\n";
                    line = "";
                }

                line += string.Format("{0} ", word);
            }
            r += line + "\n";
            return r;
        }

        private void LoadFrases()
        {
            frases[0, 0] = "So dirty it's hard to see where you are in space and time.";
            frases[0, 1] = "They have different lenses for each eye. Just for the challenge.";
            frases[0, 2] = "Shiny and stylish, it doesn't get better, right? (Tip: it does).";
            frases[0, 3] = "Your vision becomes so clear you see through other's souls.";

            frases[1, 0] = "These rags cover you only partially. It's neither sexy nor warm.";
            frases[1, 1] = "Bought for a low price at a local store. Your mum likes it.";
            frases[1, 2] = "It's always nuclear hot because it is the sum of all furs. ";
            frases[1, 3] = "Has the latest tech on thermal conservation and sex appeal.";

            frases[2, 0] = "Used for killing really weak bugs. Not cockroaches.";
            frases[2, 1] = "Helps you reaching high places so you can replace that lightbulb.";
            frases[2, 2] = "Worn by high-profile goth musicians and also you.";
            frases[2, 3] = "If Odin used boots, he would jog regularly in Asgard with these.";

            frases[3, 0] = "You slide so much your neighbours post your accidents on YouTube.";
            frases[3, 1] = "Crafted from shark jaws. Synthetic! Synthetic!";
            frases[3, 2] = "You can't moonwalk with these, but they make the game easier. Beat it!";
            frases[3, 3] = "Manufactured by ACME, they provide flexible cartoon physics.";
        }
    }
}
